﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MultiDAQ_Analysis.Calculation.Calculators;
using MultiDAQ_Analysis.Calculation.Interfaces;
using MultiDAQ_Analysis.Calculation.Results;
using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Util;
using BackgroundMeasurementResult = MultiDAQ_Analysis.Model.BackgroundMeasurementResult;

namespace MultiDAQ_Analysis.Calculation.Calculators
{
    public class BackgroundMeasurementCalculator : BaseMeasurementCalculator
    {
        public override string MeasurementType => "Background";
        public override Type ParameterType => typeof(object); // 本底测量不需要特殊参数

        protected override async Task ProcessSingleRound(MeasurementCalculationContext context, MeasurementCalculationResult result)
        {
            // 本底测量单轮处理：直接记录数据
            foreach (var kvp in context.RawData)
            {
                int channelIndex = kvp.Key;
                var (alpha, beta) = kvp.Value;

                result.ChannelResults[channelIndex] = new ChannelCalculationResult
                {
                    ChannelIndex = channelIndex,
                    AlphaResult = alpha,
                    BetaResult = beta,
                    //IsValid = ValidateBackgroundData(alpha, beta)
                };
            }

            await Task.CompletedTask;
        }

        protected override async Task ProcessFinalCalculation(MeasurementCalculationContext context, MeasurementCalculationResult result)
        {
            // 计算多轮平均值
            foreach (var channelHistory in context.HistoryData)
            {
                int channelIndex = channelHistory.Key;
                var measurements = channelHistory.Value;

                if (measurements.Count > 0)
                {
                    double alphaAvg = measurements.Average(m => m.alpha);
                    double betaAvg = measurements.Average(m => m.beta);
                    double alphaStdDev = CalculateStandardDeviation(measurements.Select(m => m.alpha).ToList());
                    double betaStdDev = CalculateStandardDeviation(measurements.Select(m => m.beta).ToList());

                    result.ChannelResults[channelIndex] = new ChannelCalculationResult
                    {
                        ChannelIndex = channelIndex,
                        AlphaResult = alphaAvg,
                        BetaResult = betaAvg,
                        AlphaUncertainty = alphaStdDev,
                        BetaUncertainty = betaStdDev,
                        //IsValid = ValidateBackgroundData(alphaAvg, betaAvg)
                    };
                }
            }

            await Task.CompletedTask;
        }

        protected override async Task SaveChannelResult(int channelIndex, ChannelCalculationResult channelResult, MeasurementCalculationResult overallResult)
        {
            var channelData = ChannelDataManager.LoadChannelData(channelIndex);

            // 保存到工作条件
            channelData.WorkConditions.AlphaBackground = channelResult.AlphaResult;
            channelData.WorkConditions.BetaBackground = channelResult.BetaResult;
            channelData.LastModified = DateTime.Now;

            // 保存测量结果
            if (channelData.MeasurementResults == null)
                channelData.MeasurementResults = new MeasurementResultData();

            channelData.MeasurementResults.BackgroundMeasurement = new BackgroundMeasurementResult
            {
                AlphaBackground = channelResult.AlphaResult,
                BetaBackground = channelResult.BetaResult,
                MeasurementTime = DateTime.Now,
                MeasurementDuration = overallResult.CalculationTime.Subtract(overallResult.CalculationTime).TotalMinutes
            };

            ChannelDataManager.SaveChannelData(channelIndex, channelData);
            await Task.CompletedTask;
        }

        private bool ValidateBackgroundData(double alpha, double beta)
        {
            return alpha >= 0 && alpha <= 1000 && beta >= 0 && beta <= 1000;
        }
    }
}